package cn.edu.sgu.www.shiro.service.impl;

import cn.edu.sgu.www.shiro.dto.UserLoginDTO;
import cn.edu.sgu.www.shiro.exception.GlobalException;
import cn.edu.sgu.www.shiro.restful.ResponseCode;
import cn.edu.sgu.www.shiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

/**
 * @author heyunlin
 * @version 1.0
 */
@Service
public class UserServiceImpl implements UserService {

    @Override
    public void login(UserLoginDTO loginDTO) {
        // shiro登录认证
        UsernamePasswordToken token = new UsernamePasswordToken(loginDTO.getUsername(), loginDTO.getPassword());
        Subject subject = SecurityUtils.getSubject();

        try {
            subject.login(token);
        } catch (IncorrectCredentialsException e) {
            throw new GlobalException(ResponseCode.FORBIDDEN, "登录失败，用户名或密码错误！");
        }

        // 设置session失效时间：永不超时
        subject.getSession().setTimeout(-1001);
    }

}